/////////////////////////////////////////////////////////////////////////////
// Copyright(c) 2012-2015 purang All Rights Reserved
// Name:        message_bond_impl.h
// Purpose:
// Author:      syy
// Modified by:
// Created:     2015/2/10 16:13
// RCS-ID:
// Licence:
/////////////////////////////////////////////////////////////////////////////
#ifndef _MESSAGE_BOND_IMPL_H_
#define _MESSAGE_BOND_IMPL_H_

#include <core/container/qbmap.h>
#include <core/sync/lock.h>
#include <qbprotocol/include/CAckManager.h>
#include <qbprotocol/include/MessageParser.h>
#include <qbprotocol/include/rdMessage.h>

#include <map>

#include "../../include/message_bond.h"
#include "network_heartbeat.h"

namespace qb {
class CMessageBondImpl : public IMessageBond,
                         public IMessageProcessorOnSubThread,
                         public INetworkHeartBeatNotify {
 public:
  CMessageBondImpl();
  virtual ~CMessageBondImpl();

  // IMessageBond
  STDMETHOD_(int32_t, Create)
  (THIS_ INetworkService* ins, IMessageKernel* kernel,
   IMessageProcess* process);
  STDMETHOD_(int32_t, Destory)(THIS_);
  STDMETHOD_(bool, RegisterDecodeFunc)(THIS_ int, qb::DecodeFunc);
  STDMETHOD_(bool, RegisterMsgProcessor)(THIS_ int, IQpidMessageProcessor*);
  STDMETHOD_(bool, UnRegisterMsgProcessor)(THIS_ int, IQpidMessageProcessor*);
  STDMETHOD_(void, SetSpecificMsgProcessor)(IQpidMessageProcessor*);

  STDMETHOD_(void, OnResponse)(THIS_ int32_t msgtype, qb::ProcessMessage msp);

  // INetworkHeartBeatNotify
  virtual void OnHeartBeat();

 private:
  // modules
  void AttachModules();
  void DetachModules();

  int32_t RequestHeartBeat();

 private:
  INetworkService* m_spNetworkService = nullptr;
  IMessageKernel* m_spMessageKernel;
  IMessageProcess* m_spMsgProcess;

  MessageParser m_Paser;
  CNetworkHeartBeat m_networkHeartBeat;

  std::multimap<int, IQpidMessageProcessor*> m_msgProcessors;
  ThreadSafeMap<int, DecodeFunc> m_msgDecodeFuncs;
  qb::base::Spinlock m_lock;
  IQpidMessageProcessor* m_specificMsgProcesser =
      nullptr;  // 关心特定requestid或者特定参数的处理

  typedef qb::base::ScopedLock<qb::base::Spinlock> Locker;
};
}  // namespace qb

#endif  // _MESSAGE_BOND_IMPL_H_
